﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace CATcpClientSender
{
    public class TCPReceive
    {
        /// <summary>
        /// 网络监听
        /// </summary>
        private TcpListener tcpListener = null;
        /// <summary>
        /// 监听进程
        /// </summary>
        private Thread acceptThread = null;
        /// <summary>
        /// 开始监听
        /// </summary>
        public void Start(int port, string localIP)
        {
            tcpListener = new TcpListener(IPAddress.Parse(localIP), port);
            tcpListener.Start(6666);
            acceptThread = new Thread(Accept);
            acceptThread.IsBackground = true;
            acceptThread.Start();
        }
        /// <summary>
        /// 开始监听
        /// </summary>
        private void Accept()
        {
            IAsyncResult acceptIR = null;
            while (true)
            {
                if (acceptIR == null)
                    acceptIR = tcpListener.BeginAcceptSocket(null, null);
                else if (acceptIR.IsCompleted)
                {
                    Socket client = tcpListener.EndAcceptSocket(acceptIR);
                    acceptIR = null;
                }
                Thread.Sleep(1);
            }
        }
    }
}
